package com.zafu.dao;

import com.zafu.entity.GoodsInfo;
import com.zafu.entity.StoreInfo;
import com.zafu.util.ElmDbConn;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * ClassName: GoodsBean
 * Package: com.zafu.dao
 * Description:
 *
 * @Author Wang
 * @Create 2024/12/20 19:46
 * @Version 1.0
 */
public class GoodsBean {

    private Connection conn;

    public GoodsBean() {
    }

    /**
     * 获取所有属于该店家的商品
     * @return
     */
     public ArrayList<GoodsInfo> GetAll() {
         conn = ElmDbConn.GetConnection();
         System.out.println(conn);

         ArrayList<GoodsInfo> list = new ArrayList<>();
         try {
             StringBuffer sBuffer = new StringBuffer();
             sBuffer.append( " select name, comment, info, image, store, price")
                     .append(" from Goods");
             PreparedStatement st = conn.prepareStatement( sBuffer.toString());
             ResultSet rs = st.executeQuery();
             while(rs.next()) {
                 GoodsInfo info = GetDataFromResultSet(rs);
                 list.add(info);
             }
         }
         catch (SQLException e) {
             System.out.printf("数据库查询失败\n" + e.getMessage());
             e.printStackTrace();
         }
         finally {
             if (conn != null) {
                 try{
                     conn.close();
                 }
                 catch ( SQLException e ) {
                     System.out.printf("关闭连接失败\n" + e.getMessage());
                 }
             }
         }
         return list;
     }
    private GoodsInfo GetDataFromResultSet(ResultSet rs ){

        GoodsInfo goodsinfo = null;
        try{
            String name = rs.getString( "name" );
            String comment = rs.getString("comment");
            String info = rs.getString("info");
            String image = rs.getString("image");
            String store = rs.getString("store");
            Double price = rs.getDouble("price");

            goodsinfo = new GoodsInfo(name, comment, info, image, store, price);

        }catch( SQLException e ){
            System.out.printf( "数据库查询失败\n" + e.getMessage()  );
            e.printStackTrace();
        }
        return goodsinfo;
    }

}
